﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using LDSP.BRL;
using LDSP.Util.Constants;

namespace LDSP.Util
{
    public class TaskPlanExport
    {
        private IDictionary<string, int> _columnOrderDic = new Dictionary<string, int>();

        public void Export(HttpServerUtility server, DataTable source, string template)
        {
            IDictionary<int, DataTable> sourceDic = ConstructDataTable(source, false);

            Export(server, sourceDic, template);
        }

        private static IDictionary<int, DataTable> ConstructDataTable(DataTable source, bool byCodification)
        {
            IDictionary<int, DataTable> sourceDic = new Dictionary<int, DataTable>();
            foreach (DataRow row in source.Rows)
            {
                if (row["favoriteID"] != null)
                {
                    int favoriteID = Int32.Parse(row["favoriteID"].ToString());
                    R_EnterpriseCodification ec = new R_EnterpriseCodification();
                    ec.GetProperties(favoriteID);

                    if (sourceDic.ContainsKey(ec.DocID))
                    {
                        sourceDic[ec.DocID].Rows.Add(row.ItemArray);
                    }
                    else
                    {
                        DataTable dt = source.Copy();
                        dt.Rows.Clear();

                        sourceDic.Add(ec.DocID, dt);
                        dt.Rows.Add(row.ItemArray);
                    }
                }
            }

            return sourceDic;
        }

        private void Export(HttpServerUtility server, IDictionary<int, DataTable> source, string template)
        {
            ExcelClass excel = new ExcelClass(template);

            //初始化列名跟列序号的映射
            DataTable dt = excel.ToDataTable(0);
            foreach (DataColumn col in dt.Columns)
            {
                _columnOrderDic.Add(col.ColumnName, col.Ordinal);
            }

            //Import all the sheets.
            foreach (int key in source.Keys)
            {
                Codification cod = new Codification();
                cod.GetProperties(key);

                string name = RemoveEnglishName(cod.Name);
                excel.ImportDataTable(excel.GenerateSheet(name), false, GetExportedDT(source[key]), 2, 1);
            }

            //Remove the 1st sheet, because it is just a template.
            if (excel.Sheets.Count > 1)
            {
                excel.RemoveSheet(0);
            }

            excel.ToExcel(@"E:\Lab\Web\ExcelImportExport\TaskPlanList.xls", DownloadType.PromptDialog);
        }

        /// <summary>
        /// 删除名称里的下划线及后面的英文
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private string RemoveEnglishName(string name)
        {
            string result = name;
            if (name.Contains("\n"))
            {
                result = name.Substring(0, name.IndexOf("\n"));
            }

            return result;
        }

        private DataTable GetExportedDT(DataTable source)
        {
            //修改显示文本。
            DataTable modifedDT = source.Copy();

            modifedDT.Columns.Add("CodificationName");
            modifedDT.Columns.Add("expiredDTs");
            modifedDT.Columns.Add("changeDTs");
            modifedDT.Columns.Add("statuss");

            for (int i = 0; i < source.Rows.Count; i++)
            {
                Plan ett = new Plan();
                ett.GetProperties(source.Rows[i]);
                modifedDT.Rows[i]["CodificationName"] = ett.EnterpriseCodification.Codification.Name;
                modifedDT.Rows[i]["expiredDTs"] = FormatDT(ett.ExpiredDT);
                modifedDT.Rows[i]["changeDTs"] = FormatDT(ett.ChangeDT);
                modifedDT.Rows[i]["statuss"] = ((TaskStatus)ett.Status).ToString();
            }

            //导出.
            DataTable dt = new DataTable();
            dt.Columns.Add(TaskPlanColumnNames.Codification_Name);
            dt.Columns.Add(TaskPlanColumnNames.Pricipal);
            dt.Columns.Add(TaskPlanColumnNames.Name);
            dt.Columns.Add(TaskPlanColumnNames.Execution);
            dt.Columns.Add(TaskPlanColumnNames.Expired_Date);
            dt.Columns.Add(TaskPlanColumnNames.Process);
            dt.Columns.Add(TaskPlanColumnNames.Update_Date);
            dt.Columns.Add(TaskPlanColumnNames.Comments);
            dt.Columns.Add(TaskPlanColumnNames.Status);

            //设定列号
            if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Codification_Name))
            {
                dt.Columns[TaskPlanColumnNames.Codification_Name].SetOrdinal(_columnOrderDic[TaskPlanColumnNames.Codification_Name]);
            }
            if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Pricipal))
            {
                dt.Columns[TaskPlanColumnNames.Pricipal].SetOrdinal(_columnOrderDic[TaskPlanColumnNames.Pricipal]);
            }
            if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Name))
            {
                dt.Columns[TaskPlanColumnNames.Name].SetOrdinal(_columnOrderDic[TaskPlanColumnNames.Name]);
            }
            if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Execution))
            {
                dt.Columns[TaskPlanColumnNames.Execution].SetOrdinal(_columnOrderDic[TaskPlanColumnNames.Execution]);
            }
            if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Expired_Date))
            {
                dt.Columns[TaskPlanColumnNames.Expired_Date].SetOrdinal(_columnOrderDic[TaskPlanColumnNames.Expired_Date]);
            }
            if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Process))
            {
                dt.Columns[TaskPlanColumnNames.Process].SetOrdinal(_columnOrderDic[TaskPlanColumnNames.Process]);
            }
            if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Update_Date))
            {
                dt.Columns[TaskPlanColumnNames.Update_Date].SetOrdinal(_columnOrderDic[TaskPlanColumnNames.Update_Date]);
            }
            if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Comments))
            {
                dt.Columns[TaskPlanColumnNames.Comments].SetOrdinal(_columnOrderDic[TaskPlanColumnNames.Comments]);
            }
            if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Status))
            {
                dt.Columns[TaskPlanColumnNames.Status].SetOrdinal(_columnOrderDic[TaskPlanColumnNames.Status]);
            }

            //导出列
            foreach (DataRow row in modifedDT.Rows)
            {
                DataRow r = dt.NewRow();
                if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Codification_Name))
                {
                    r[_columnOrderDic[TaskPlanColumnNames.Codification_Name]] = row["CodificationName"];
                }

                if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Pricipal))
                {
                    r[_columnOrderDic[TaskPlanColumnNames.Pricipal]] = row["person"];
                }

                if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Name))
                {
                    r[_columnOrderDic[TaskPlanColumnNames.Name]] = row["name"];
                }

                if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Execution))
                {
                    r[_columnOrderDic[TaskPlanColumnNames.Execution]] = row["department"];
                }

                if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Expired_Date))
                {
                    r[_columnOrderDic[TaskPlanColumnNames.Expired_Date]] = row["expiredDTs"];
                }

                if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Process))
                {
                    r[_columnOrderDic[TaskPlanColumnNames.Process]] = row["progress"];
                }

                if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Update_Date))
                {
                    r[_columnOrderDic[TaskPlanColumnNames.Update_Date]] = row["changeDTs"];
                }

                if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Comments))
                {
                    r[_columnOrderDic[TaskPlanColumnNames.Comments]] = row["comment"];
                }

                if (_columnOrderDic.ContainsKey(TaskPlanColumnNames.Status))
                {
                    r[_columnOrderDic[TaskPlanColumnNames.Status]] = row["statuss"];
                }

                dt.Rows.Add(r);
            }

            return dt;
        }

        private string FormatDT(DateTime dt, bool isDateTime = false)
        {
            if (dt == DateTime.MaxValue)
            {
                return "";
            }
            return isDateTime ? dt.ToString("yyyy-MM-dd HH:mm:ss") : dt.ToString("yyyy-MM-dd");
        }
    }
}